﻿using System.Collections.Generic;
using System.Threading;
using MediatR;

namespace Elasticsearch.Synchronize.Domain.SeedWork
{
    public abstract class Entity
    {
        /// <summary>
        /// 领域事件协调器
        /// </summary>
        private readonly IMediator _mediator;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mediator">领域事件协调器</param>
        protected Entity(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// 领域事件集合
        /// </summary>
        private List<INotification> _domainEvents;

        /// <summary>
        /// 领域事件集合
        /// </summary>
        public List<INotification> DomainEvents => _domainEvents;

        /// <summary>
        /// 判断是否是临时对象
        /// </summary>
        /// <remarks>
        /// 判断是已经存在的领域对象还是新创建出来的领域对象
        /// </remarks>
        /// <returns></returns>
        public abstract bool IsTransient();

        /// <summary>
        /// 向领域事件集合里添加事件
        /// </summary>
        /// <param name="eventItem"></param>
        public void AddDomainEvent(INotification eventItem)
        {
            _domainEvents = _domainEvents ?? new List<INotification>();
            _domainEvents.Add(eventItem);
        }

        /// <summary>
        /// 删除领域事件集合里的事件
        /// </summary>
        /// <param name="eventItem"></param>
        public void RemoveDomainEvent(INotification eventItem)
        {
            if (_domainEvents is null)
            {
                return;
            }

            _domainEvents.Remove(eventItem);
        }

        /// <summary>
        /// 异步的发送领域事件
        /// </summary>
        /// <param name="eventItem">领域事件</param>
        /// <returns></returns>
        public void DomainEventPublish(INotification eventItem)
        {
            _mediator.Publish(eventItem);
        }
    }
}